package com.zhilianbao.leyaogo.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.util.LongSparseArray;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.bql.changeskin.constant.SkinConfig;
import com.bql.convenientlog.CLog;
import com.bql.pickphotos.PickPhotos;
import com.bql.pulltorefreshandloadmore.loadmoreview.LoadMoreRecyclerView;
import com.bql.sharesdk.utils.ShareUtil;
import com.bql.utils.CheckUtils;
import com.bql.utils.DeviceUtils;
import com.bql.utils.EventManager;
import com.bql.utils.FileUtils;
import com.bql.utils.NetworkUtils;
import com.bql.utils.NotificationUtils;
import com.bql.utils.NumberUtlis;
import com.bql.variousdialog.listener.OnDialogItemClickListener;
import com.bql.variousdialog.widget.ActionSheetDialog;
import com.google.gson.Gson;
import com.xiaomi.channel.commonutils.logger.LoggerInterface;
import com.xiaomi.mipush.sdk.Logger;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.xiaomi.mipush.sdk.MiPushMessage;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.CacheConfig;
import com.zhilianbao.leyaogo.constants.HttpConfig;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.constants.LoginConfig;
import com.zhilianbao.leyaogo.constants.PushConfig;
import com.zhilianbao.leyaogo.events.UserEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.convert.GsonConvert;
import com.zhilianbao.leyaogo.listener.OnLoginListener;
import com.zhilianbao.leyaogo.model.entity.BaseBean;
import com.zhilianbao.leyaogo.model.response.Coupon.CouponGood;
import com.zhilianbao.leyaogo.model.response.UserLoginInfo;
import com.zhilianbao.leyaogo.model.response.address.Address;
import com.zhilianbao.leyaogo.model.response.category.GoodsDetails;
import com.zhilianbao.leyaogo.model.response.category.SkuEntity;
import com.zhilianbao.leyaogo.model.response.category.SkuMapEntity;
import com.zhilianbao.leyaogo.model.response.login.WXAccessTokenInfo;
import com.zhilianbao.leyaogo.model.response.me.MeRedDotResponse;
import com.zhilianbao.leyaogo.model.response.me.UserDetailsInfo;
import com.zhilianbao.leyaogo.model.response.shoppingcart.ActivityFree;
import com.zhilianbao.leyaogo.model.response.shoppingcart.ActivitySubtract;
import com.zhilianbao.leyaogo.model.response.shoppingcart.BaseActivityInfo;
import com.zhilianbao.leyaogo.model.response.shoppingcart.Express;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsSKU;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsStock;
import com.zhilianbao.leyaogo.model.response.shoppingcart.OrderItem;
import com.zhilianbao.leyaogo.model.response.shoppingcart.ShopActivityInfo;
import com.zhilianbao.leyaogo.model.response.shoppingcart.ShoppingCartGood;
import com.zhilianbao.leyaogo.receiver.MiPushMessageReceiver;
import com.zhilianbao.leyaogo.receiver.NotificationClickReceiver;
import com.zhilianbao.leyaogo.ui.activity.LoginActivity;
import com.zhilianbao.leyaogo.ui.activity.QuickLoginActivity;
import com.zhilianbao.leyaogo.ui.activity.goodscategory.GoodsActivity;
import com.zhilianbao.leyaogo.ui.activity.home.GoodsClassifyListActivity;
import com.zhilianbao.leyaogo.ui.activity.home.SpecialActivityDetailsActivity;
import com.zhilianbao.leyaogo.ui.activity.me.moneyaccount.RechargeSaleCardActivity;
import com.zhilianbao.leyaogo.ui.fragment.shoppingcart.ShoppingCartFragment;
import com.zhilianbao.okhttputils.OkHttpUtils;
import com.zlb.lxlibrary.service.LeXiuInitService;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

import static com.bql.utils.NumberUtlis.mul;
import static com.zhilianbao.leyaogo.ui.fragment.shoppingcart.ShoppingCartFragment.FREE;
import static com.zhilianbao.leyaogo.ui.fragment.shoppingcart.ShoppingCartFragment.STATE_DEL;
import static com.zhilianbao.leyaogo.ui.fragment.shoppingcart.ShoppingCartFragment.STATE_NOT_ENOUGH;
import static com.zhilianbao.leyaogo.ui.fragment.shoppingcart.ShoppingCartFragment.STATE_OUT_STOCK;
import static com.zhilianbao.leyaogo.ui.fragment.shoppingcart.ShoppingCartFragment.STATE_USEABLE;
import static com.zhilianbao.leyaogo.ui.fragment.shoppingcart.ShoppingCartFragment.SUBTRACT;

/**
 * ClassName: Utils <br>
 * Description: <br>
 * Author: Cyarie <br>
 * Created: 2016/7/19 16:41 <br>
 * Update Time：<br>
 * Update Description：<br>
 */
public class Utils {

    /**
     * 保存用户登录信息
     *
     * @param o
     */
    public static void putUserLoginInfo(UserLoginInfo o) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.USER_LOGIN_INFO, o);
    }

    /**
     * 获取用户登录信息
     *
     * @return
     */
    public static UserLoginInfo getUserLoginInfo() {
        return (UserLoginInfo) LeYaoGoApplication.getDataKeeper().get(CacheConfig.USER_LOGIN_INFO);
    }


    /**
     * 判断用户是否登录
     *
     * @param startLoginPage 是否跳转至登录页面
     * @return
     */
    public static boolean isUserLogin(boolean startLoginPage) {
        if (getUserLoginInfo() != null) {
            return true;
        } else if (startLoginPage) {
            Intent intent = new Intent(LeYaoGoApplication.getContext(), QuickLoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            LeYaoGoApplication.getContext().startActivity(intent);
            return false;
        }
        return false;
    }

    /**
     * 判断用户是否登录
     *
     * @param startLoginPage 是否跳转至登录页面
     * @param loginState     逻辑状态 用于登录成功后继续执行下一步操作
     * @return
     */
    public static boolean isUserLogin(boolean startLoginPage, int loginState) {
        if (getUserLoginInfo() != null) {
            return true;
        } else if (startLoginPage) {
            Intent intent = new Intent(LeYaoGoApplication.getContext(), QuickLoginActivity.class);
            intent.putExtra(IntentConfig.LOGIC_CODE, loginState);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            LeYaoGoApplication.getContext().startActivity(intent);
            return false;
        }
        return false;
    }

    /**
     * 判断用户是否登录
     *
     * @return
     */
    public static boolean justIsUserLogin() {
        if (getUserLoginInfo() != null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 保存登录用户名
     *
     * @param name
     */
    public static void putUserLoginName(String name) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.USER_LOGIN_NAME, name);
    }

    /**
     * 获取登录用户名
     *
     * @return
     */
    public static String getUserLoginName() {
        return LeYaoGoApplication.getDataKeeper().get(CacheConfig.USER_LOGIN_NAME, "");
    }

    /**
     * 保存定位
     *
     * @param location 定位城市
     */
    public static void putLocation(String location) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.LOCATION, getLocationWithoutSuffix(location));
    }

    /**
     * 获取城市
     *
     * @param location 定位城市
     */
    public static String getLocationWithoutSuffix(String location) {
        if (location.contains(LeYaoGoApplication.getContext().getString(R.string.city_suffix))) {
            String str = location.replace(LeYaoGoApplication.getContext().getString(R.string.city_suffix), "");
            return str;
        }
        return location;
    }


    /**
     * 根据城市获取城市编码
     *
     * @param city
     * @return
     */
    public static String getCityCode(String city) {
        ArrayList<BaseBean> cityCodeList = Utils.getCityCodeList();
        if (!CheckUtils.isEmpty(cityCodeList)) {
            for (int i = 0; i < cityCodeList.size(); i++) {
                if (cityCodeList.get(i).getName().contains(city)) {
                    return cityCodeList.get(i).getId();
                }
            }
        } else {
            return "0";
        }
        return "0";
    }

    /**
     * 获取定位
     *
     * @return
     */
    public static String getLocation() {
        return LeYaoGoApplication.getDataKeeper().get(CacheConfig.LOCATION, "");
    }

    /**
     * 保存运营商Id
     *
     * @param supplierId
     */
    public static void putSupplierId(long supplierId) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.SUPPLIER_ID, supplierId);
    }

    /**
     * 获取运营商Id
     *
     * @return
     */
    public static long getSupplierId() {
        return LeYaoGoApplication.getDataKeeper().get(CacheConfig.SUPPLIER_ID, 0);
    }


    /**
     * 保存融云客服Id
     *
     * @param strVal1
     */
    public static void putRongyunId(String strVal1) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.RONGYUN_ID, strVal1);
    }

    /**
     * 获取融云客服Id
     *
     * @return
     */
    public static String getRongyunId() {
        return LeYaoGoApplication.getDataKeeper().get(CacheConfig.RONGYUN_ID, "");
    }

    /**
     * 保存是否首次进入应用
     *
     * @param first
     */
    public static void putFirstEnter(boolean first) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.FIRST_ENTER, first);
    }

    /**
     * 获取是否首次进入应用
     *
     * @return
     */
    public static boolean getFirstEnter() {
        return LeYaoGoApplication.getDataKeeper().get(CacheConfig.FIRST_ENTER, true);
    }


    /**
     * 保存搜索历史 最对10条数据
     *
     * @param hisList
     */
    public static void saveSearchHistory(List<String> hisList) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.SEARCH_HISTORY, hisList);
    }

    /**
     * 获取搜索历史
     *
     * @return
     */
    public static List<String> getSearchHistory() {
        return (List<String>) LeYaoGoApplication.getDataKeeper().get(CacheConfig.SEARCH_HISTORY);
    }

    /**
     * 清空搜索历史
     *
     * @return
     */
    public static void clearSearchHistory() {
        LeYaoGoApplication.getDataKeeper().remove(CacheConfig.SEARCH_HISTORY);
    }

    /**
     * 保存城市Json
     *
     * @param address
     */
    public static void putDictionary(String address) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.ALL_DICTIONARY, address);
    }

    /**
     * 获取城市Json
     *
     * @return
     */
    public static String getDictionary() {
        return LeYaoGoApplication.getDataKeeper().get(CacheConfig.ALL_DICTIONARY, "");
    }


    /**
     * 保存上次支付方式
     *
     * @param type 支付方式  1 微信  2 支付宝  3 余额
     */
    public static void putLastPayType(int type) {
        LeYaoGoApplication.getDataKeeper().putInt(CacheConfig.LAST_PAY_TYPE, type);
    }

    /**
     * 获取上次支付方式
     *
     * @return
     */
    public static int getLastPayType() {
        return LeYaoGoApplication.getDataKeeper().getInt(CacheConfig.LAST_PAY_TYPE, -1);
    }


    /**
     * 保存上次充值方式
     *
     * @param type 支付方式  1 微信  2 支付宝
     */
    public static void putLastRechargeType(int type) {
        LeYaoGoApplication.getDataKeeper().putInt(CacheConfig.LAST_RECHARGE_TYPE, type);
    }

    /**
     * 获取上次充值方式
     *
     * @return
     */
    public static int getLastRechargeType() {
        return LeYaoGoApplication.getDataKeeper().getInt(CacheConfig.LAST_RECHARGE_TYPE, 0);
    }


    /**
     * 保存用户详细信息
     *
     * @param detailsInfo
     */
    public static void putUserInfo(UserDetailsInfo detailsInfo) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.USER_DETAILS_INFO, detailsInfo);
    }

    /**
     * 获取用户详细信息
     *
     * @return
     */
    public static UserDetailsInfo getUserInfo() {
        return (UserDetailsInfo) LeYaoGoApplication.getDataKeeper().get(CacheConfig.USER_DETAILS_INFO);
    }

    /**
     * 保存我的页面红点数据
     *
     * @param meRedDotResponse
     */
    public static void putMeRedDot(MeRedDotResponse meRedDotResponse) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.ME_RED_DOT, meRedDotResponse);
    }

    /**
     * 获取我的页面红点数据
     *
     * @return
     */
    public static MeRedDotResponse getMeRedDot() {
        return (MeRedDotResponse) LeYaoGoApplication.getDataKeeper().get(CacheConfig.ME_RED_DOT);
    }

    /**
     * 保存融云token
     *
     * @param token
     */
    public static void putRongyunToken(String token) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.RONG_YUN_TOKEN, token);
    }

    /**
     * 获取融云token
     *
     * @return
     */
    public static String getRongyunToken() {
        return LeYaoGoApplication.getDataKeeper().get(CacheConfig.RONG_YUN_TOKEN, "");
    }


    /**
     * 修改用户信息
     *
     * @param userDetailsInfo
     * @param birthday
     * @param sex
     * @param pic
     * @param nickName
     */
    public static void updateUserInfor(Context context, UserDetailsInfo userDetailsInfo, long optUserId, String tokenId, long userId, String birthday, int sex, String pic, String realName, String nickName) {
        AccountApi.updateUserInfo(context, optUserId, tokenId, userId, birthday, sex, pic, realName, nickName, new DialogCallback<Object>(context) {
            @Override
            public void onSuccess(Object o, Call call, Response response) {
                Utils.putUserInfo(userDetailsInfo);
                LeXiuInitService.getInstance().onUserInfoChange(userDetailsInfo.getUserAlias(), Utils.returnUrlShow(userDetailsInfo.getUserPic()), userDetailsInfo.getSex() + "");
                EventBus.getDefault().post(new EventManager(UserEventCode.MSG_CODE_MODIFY_USERINFO, userDetailsInfo));
            }
        });
    }

    /**
     * 更新用户本地头像
     *
     * @param userPic
     */
    public static void updateUserPic(String userPic) {
        UserDetailsInfo userDetailsInfo = getUserInfo();
        if (userDetailsInfo != null) {
            userDetailsInfo.setUserPic(userPic);
            putUserInfo(userDetailsInfo);
        }
        UserLoginInfo userLoginInfo = getUserLoginInfo();
        if (userLoginInfo != null) {
            userLoginInfo.setUserPic(userPic);
            putUserLoginInfo(userLoginInfo);
        }

    }

    /**
     * 更新本地用户名
     *
     * @param alias
     */
    public static void updateUserAlisa(String alias) {
        UserDetailsInfo userDetailsInfo = getUserInfo();
        if (userDetailsInfo != null) {
            userDetailsInfo.setUserAlias(alias);
            putUserInfo(userDetailsInfo);
        }
        UserLoginInfo userLoginInfo = getUserLoginInfo();
        if (userLoginInfo != null) {
            userLoginInfo.setUserAlias(alias);
            putUserLoginInfo(userLoginInfo);
        }

    }

    /**
     * 更新本地用户信息
     *
     * @param nickName
     * @param realName
     * @param sex
     * @param birthday
     * @param province
     * @param city
     * @param area
     * @param strAddress
     * @param address
     */
    public static void updateUserInfo(String nickName, String realName, String sex, String birthday, String province, String
            city, String area, String strAddress, String address) {
        UserDetailsInfo userDetailsInfo = getUserInfo();
        if (userDetailsInfo != null) {
            userDetailsInfo.setNickName(nickName);
            userDetailsInfo.setRealName(realName);
            userDetailsInfo.setSex(NumberUtlis.convertToint(sex, 2));
            userDetailsInfo.setBirthday(birthday);
            userDetailsInfo.setProvince(province);
            userDetailsInfo.setCity(city);
            userDetailsInfo.setArea(area);
            userDetailsInfo.setStrAddress(strAddress);
            userDetailsInfo.setAddress(address);
            putUserInfo(userDetailsInfo);
        }
    }


    /**
     * 清除用户相关数据
     *
     * @return
     */
    public static void clear() {
        LeYaoGoApplication.getDataKeeper().remove(CacheConfig.USER_LOGIN_INFO);
        LeYaoGoApplication.getDataKeeper().remove(CacheConfig.USER_DETAILS_INFO);
        LeYaoGoApplication.getDataKeeper().remove(CacheConfig.SEARCH_HISTORY);
        //        LeYaoGoApplication.getDataKeeper().remove(CacheConfig.LAST_PAY_TYPE);//测试的说，退出不清除支付记录
        LeYaoGoApplication.getDataKeeper().remove(CacheConfig.DEFAULT_ADDRESS);
        LeYaoGoApplication.getDataKeeper().remove(CacheConfig.SHOPPING_CART_CHECK_ID);
        LeYaoGoApplication.getDataKeeper().remove(CacheConfig.RONG_YUN_TOKEN);
    }


    /**
     * 更新TokenId
     *
     * @param tokenId
     */
    public static void updateTokenId(String tokenId) {
        UserLoginInfo userLogin = getUserLoginInfo();
        if (userLogin != null) {
            userLogin.setTokenId(tokenId);
            putUserLoginInfo(userLogin);
        }
    }


    /**
     * 更新手机号码
     *
     * @param mobile
     */
    public static void updateMobile(String mobile) {
        UserLoginInfo userLogin = getUserLoginInfo();
        if (userLogin != null) {
            userLogin.setUserMobile(mobile);
            putUserLoginInfo(userLogin);
        }
        UserDetailsInfo userDetailsInfo = getUserInfo();
        if (userDetailsInfo != null) {
            userDetailsInfo.setUserMobile(mobile);
            putUserInfo(userDetailsInfo);
        }
    }


    /**
     * activity跳转
     *
     * @param nowActivity    当前的activity
     * @param targetActivity 目标的activity
     */
    public static void startActivity(Activity nowActivity, Class<?> targetActivity) {
        Intent intent = new Intent(nowActivity, targetActivity);
        nowActivity.startActivity(intent);
    }


    /**
     * 带参数的activity跳转
     *
     * @param nowActivity    当前的activity
     * @param targetActivity 目标的activity
     * @param bundle         bundle参数
     */
    public static void startActivity(Activity nowActivity, Class<?> targetActivity, Bundle bundle) {
        if (bundle == null) {
            startActivity(nowActivity, targetActivity);
        } else {
            Intent intent = new Intent(nowActivity, targetActivity);
            intent.putExtras(bundle);
            nowActivity.startActivity(intent);
        }

    }


    /**
     * 带参数的activity跳转
     *
     * @param targetActivity 目标的activity
     * @param bundle         bundle参数
     */
    public static void startNewTaskActivity(Class<?> targetActivity, Bundle bundle) {
        Intent intent = new Intent(LeYaoGoApplication.getContext(), targetActivity);
        intent.setFlags(
                Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        intent.putExtras(bundle);
        LeYaoGoApplication.getContext().startActivity(intent);

    }

    /**
     * 带参数的跳转
     *
     * @param targetActivity
     * @param bundle
     */
    public static void startActivity(Class<?> targetActivity, Bundle bundle) {
        Intent intent = new Intent(LeYaoGoApplication.getContext(), targetActivity);
        intent.putExtras(bundle);
        LeYaoGoApplication.getContext().startActivity(intent);

    }

    /**
     * activity跳转  回传数据
     *
     * @param nowActivity    当前的activity
     * @param targetActivity 目标的activity
     * @param requestCode    请求码
     */
    public static void startActivityForResult(Activity nowActivity, Class<?> targetActivity, int requestCode) {
        Intent intent = new Intent(nowActivity, targetActivity);
        nowActivity.startActivityForResult(intent, requestCode);
    }

    /**
     * 带参数的activity跳转  回传数据
     *
     * @param nowActivity    当前的activity
     * @param targetActivity 目标的activity
     * @param requestCode    请求码
     * @param bundle         参数
     */
    public static void startActivityForResult(Activity nowActivity, Class<?> targetActivity, int requestCode, Bundle bundle) {
        Intent intent = new Intent(nowActivity, targetActivity);
        intent.putExtras(bundle);
        nowActivity.startActivityForResult(intent, requestCode);
    }

    /**
     * 启动Activity并清除同一栈中的其他activity
     *
     * @param nowActivity
     * @param targetActivity
     */
    public static void startActivityClearTop(Activity nowActivity, Class<?> targetActivity) {
        Intent intent = new Intent(nowActivity, targetActivity);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        nowActivity.startActivity(intent);
    }


    /**
     * 动态设置ListView的高度
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if (listView == null)
            return;

        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }


    /**
     * 带参数启动Activity并清除同一栈中的其他activity
     *
     * @param nowActivity
     * @param targetActivity
     */
    public static void startActivityClearTop(Activity nowActivity, Class<?> targetActivity, Bundle bundle) {
        Intent intent = new Intent(nowActivity, targetActivity);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        nowActivity.startActivity(intent);
    }


    /**
     * 网络是否连接
     *
     * @return
     */
    public static boolean isNetConnected() {
        return NetworkUtils.isConnected(LeYaoGoApplication.getContext());
    }


    /**
     * 返回URL 有前缀http直接返回 否则加上前缀返回
     *
     * @param url
     * @return
     */
    public static String returnUrlShow(String url) {
        if (CheckUtils.isEmpty(url)) {
            return null;
        }
        if (url.contains(HttpConfig.URL_CLOUD_SHOW)) {
            return url;
        } else {
            return HttpConfig.URL_CLOUD_SHOW + url;
        }
    }


    /**
     * 高亮字体
     *
     * @param view    TextView
     * @param oriStr  源字符画
     * @param keyword 关键字符串
     * @param color   颜色
     */
    public static void highlightStr(TextView view, String oriStr, String keyword, int color) {
        int start = oriStr.indexOf(keyword);
        SpannableStringBuilder style = new SpannableStringBuilder(oriStr);
        style.setSpan(new ForegroundColorSpan(color), start, keyword.length() + start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        view.setText(style);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(float dpValue) {
        return DeviceUtils.dp2px(LeYaoGoApplication.getContext(), dpValue);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dp(float pxValue) {
        return DeviceUtils.px2dp(LeYaoGoApplication.getContext(), pxValue);
    }

    /**
     * 从 px(像素) 的单位 转成为 sp
     */
    public static int px2sp(float pxValue) {
        return DeviceUtils.px2sp(LeYaoGoApplication.getContext(), pxValue);
    }

    /**
     * 从 sp 的单位 转成为 px(像素)
     */
    public static int sp2px(float spValue) {
        return DeviceUtils.sp2px(LeYaoGoApplication.getContext(), spValue);
    }


    /**
     * 获取屏幕宽度
     *
     * @return
     */
    public static int getScreenWidth() {
        return LeYaoGoApplication.getContext().getResources().getDisplayMetrics().widthPixels;
    }


    /**
     * 获取屏幕高度
     *
     * @return
     */
    public static int getScreenHeight() {
        return LeYaoGoApplication.getContext().getResources().getDisplayMetrics().heightPixels;
    }


    /**
     * 获取文件MD5+后缀
     *
     * @param filePath 文件路径
     * @return
     * @throws FileNotFoundException
     */
    public static String getMd5ByFilePath(String filePath) {
        FileInputStream in = null;
        String value = null;
        try {
            if (!FileUtils.isFileExist(filePath))
                throw new FileNotFoundException(LeYaoGoApplication.getContext().getString(R.string.file_no_exist));

            File file = new File(filePath);
            in = new FileInputStream(file);
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value + "." + FileUtils.getFileExtension(filePath);
    }


    //上次点击时间
    private static long sLastCLickTime;

    /**
     * 是否快速双击
     *
     * @return
     */
    public static boolean isFastDoubleClick() {
        long now = System.currentTimeMillis();
        long interval = now - sLastCLickTime;
        if (interval > 0 && interval < 500) {
            return true;
        }
        sLastCLickTime = now;
        return false;

    }

    /**
     * 注册小米 信鸽 百度推送平台
     */
    public static void registerPush() {
        registerMiPush();
        //        registerTecentXGPush();
        //        registerBaiDuPush();
    }


    /**
     * 反注册小米 信鸽 百度推送平台
     */
    public static void unregisterPush() {
        unregisterMiPush();
        //        unregisterTecentXGPush();
        //        unregisterBaiDuPush();
    }


    /**
     * 注册百度推送
     */
    //    private static void registerBaiDuPush() {
    //        PushSettings.enableDebugMode(LeYaoGoApplication.getContext(), BuildConfig.LOG_ENABLE);
    //        PushManager.startWork(LeYaoGoApplication.getContext(), PushConstants.LOGIN_TYPE_API_KEY, PushConfig.BAIDU_PUSH_API_KEY);
    //
    //    }

    /**
     * 反注册百度推送
     */
    //    private static void unregisterBaiDuPush() {
    //        PushManager.stopWork(LeYaoGoApplication.getContext());
    //    }


    /**
     * 注册腾讯信鸽推送
     */
    //    private static void registerTecentXGPush() {
    //        if (CheckUtils.isAppOnForeground(LeYaoGoApplication.getContext()) && !LeYaoGoApplication.getDataKeeper().get(PushConfig.PREF_KEY_XG_PUSH, false)) {
    //            //Tecent信鸽推送调试
    //            XGPushConfig.enableDebug(LeYaoGoApplication.getContext(), BuildConfig.LOG_ENABLE);
    //            XGPushManager.registerPush(LeYaoGoApplication.getContext(), Utils.getUserLoginInfo().getUserId() + "");
    //        }
    //    }

    /**
     * 反注册腾讯信鸽推送
     */
    //    private static void unregisterTecentXGPush() {
    //        XGPushManager.unregisterPush(LeYaoGoApplication.getContext());
    //
    //    }

    /**
     * 注册小米推送
     */
    private static void registerMiPush() {
        //初始化小米推送服务  因为推送服务XMPushService在AndroidManifest.xml中设置为运行在另外一个进程，这导致本Application会被实例化两次，所以我们需要让应用的主进程初始化。
        if (CheckUtils.isAppOnForeground(LeYaoGoApplication.getContext()) && !LeYaoGoApplication.getDataKeeper().get(PushConfig.PREF_KEY_MI_PUSH, false) && Utils.getUserLoginInfo() != null) {
            MiPushClient.registerPush(LeYaoGoApplication.getContext(), PushConfig.MI_PUSH_APP_ID, PushConfig.MI_PUSH_APP_KEY);
            //开启小米推送logcat调试
            LoggerInterface newLogger = new LoggerInterface() {
                @Override
                public void setTag(String tag) {
                    // ignore
                }

                @Override
                public void log(String content, Throwable t) {
                    CLog.i(MiPushMessageReceiver.TAG, "content=" + content + "Throwable=" + t);
                }

                @Override
                public void log(String content) {
                    CLog.i(MiPushMessageReceiver.TAG, "content=" + content);
                }
            };
            Logger.setLogger(LeYaoGoApplication.getContext(), newLogger);
        }

    }


    /**
     * 反注册小米推送
     */
    private static void unregisterMiPush() {
        MiPushClient.unregisterPush(LeYaoGoApplication.getContext());
        LeYaoGoApplication.getDataKeeper().put(PushConfig.PREF_KEY_MI_PUSH, false);
    }


    /**
     * 发送百度通知
     *
     * @param jsonMessage
     */
    public static void sendBaiDuPushNotification(String jsonMessage) {
        //        NotifyParams notifyParams = new Gson().fromJson(jsonMessage, NotifyParams.class);
        //        if (notifyParams != null) {
        //            sendNotification(notifyParams.getTitle(), notifyParams.getDescription(), notifyParams.getCustom_content().getRoomId());
        //        }
    }

    /**
     * 发送信鸽通知
     */
    //    public static void sendXGPushNotification(XGPushTextMessage message) {
    //        int roomId;
    //        try {
    //            JSONObject jsonObject = new JSONObject(message.getCustomContent());
    //            roomId = jsonObject.optInt("roomId", 0);
    //        } catch (Exception e) {
    //            return;
    //        }
    //
    //        if (message != null) {
    //            sendNotification(message.getTitle(), message.getContent(), roomId);
    //        }
    //    }


    /**
     * 发送小米通知
     */
    public static void sendMiNotification(MiPushMessage miPushMessage) {
        int roomId = 0;
        Map<String, String> stringMap = miPushMessage.getExtra();
        if (stringMap != null) {
            roomId = Integer.valueOf(stringMap.get("roomId"));
        }
        if (miPushMessage != null) {
            sendNotification(miPushMessage.getTitle(), miPushMessage.getDescription(), roomId);
        }
    }

    /**
     * 发送通知
     *
     * @param title   标题
     * @param content 内容
     * @param roomId  房间ID
     */
    public static void sendNotification(String title, String content, int roomId) {
        Intent intent = new Intent(LeYaoGoApplication.getContext(), NotificationClickReceiver.class);
        intent.setAction(PushConfig.ACTION_CLICK_NOTIFICATION);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);
        PendingIntent pIntent = PendingIntent.getBroadcast(LeYaoGoApplication.getContext(),
                roomId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        int smallIcon = R.mipmap.ic_launcher;
        NotificationUtils notificationUtils = new NotificationUtils(LeYaoGoApplication.getContext(), roomId);
        notificationUtils.notifyMoreLine(pIntent, smallIcon, title, title, content, true, true, false);
    }


    /**
     * 判断Avtivity是否存在
     *
     * @param cls 要判断的Activity
     * @return
     */
    public static boolean isActivityExist(Class<?> cls) {
        Intent intent = new Intent(LeYaoGoApplication.getContext(), cls);
        ComponentName cmpName = intent.resolveActivity(LeYaoGoApplication.getContext().getPackageManager());
        if (cmpName != null) { // 说明系统中存在这个activity
            ActivityManager am = (ActivityManager) LeYaoGoApplication.getContext().getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.topActivity.equals(cmpName)) { // 说明它已经启动了
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取用户客户端设备信息
     *
     * @return
     */
    public static String getUserAgent() {
        String webUserAgent = null;
        try {
            Class<?> sysResCls = Class.forName("com.android.internal.R$string");
            Field webUserAgentField = sysResCls.getDeclaredField("web_user_agent");
            Integer resId = (Integer) webUserAgentField.get(null);
            webUserAgent = LeYaoGoApplication.getContext().getString(resId);
        } catch (Exception e) {
            // We have nothing to do
        }
        if (TextUtils.isEmpty(webUserAgent)) {
            webUserAgent = "Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/533.1 (KHTML, like Gecko) Version/5.0 %sSafari/533.1";
        }

        Locale locale = Locale.getDefault();
        StringBuffer buffer = new StringBuffer();
        // Add version
        final String version = Build.VERSION.RELEASE;
        if (version.length() > 0) {
            buffer.append(version);
        } else {
            // default to "1.0"
            buffer.append("1.0");
        }
        buffer.append("; ");
        final String language = locale.getLanguage();
        if (language != null) {
            buffer.append(language.toLowerCase(locale));
            final String country = locale.getCountry();
            if (!TextUtils.isEmpty(country)) {
                buffer.append("-");
                buffer.append(country.toLowerCase(locale));
            }
        } else {
            // default to "en"
            buffer.append("en");
        }
        // add the model for the release build
        if ("REL".equals(Build.VERSION.CODENAME)) {
            final String model = Build.MODEL;
            if (model.length() > 0) {
                buffer.append("; ");
                buffer.append(model);
            }
        }
        final String id = Build.ID;
        if (id.length() > 0) {
            buffer.append(" Build/");
            buffer.append(id);
        }
        return String.format(webUserAgent, buffer, "Mobile ");
    }

    /**
     * 获取客户端可以支持的语言
     *
     * @return
     */
    public static String getAcceptLanguage() {
        Locale locale = Locale.getDefault();
        String language = locale.getLanguage();
        String country = locale.getCountry();
        StringBuilder acceptLanguageBuilder = new StringBuilder(language);
        if (!TextUtils.isEmpty(country))
            acceptLanguageBuilder.append('-').append(country).append(',').append(language).append(";q=0.8");
        return acceptLanguageBuilder.toString();
    }


    /**
     * 获取公司皮肤后缀名
     *
     * @param type 公司类型  0 集团  2 子公司 3 代理商
     * @return
     */
    public static String getCompanySkinSuffix(int type) {
        String suffix = "";
        switch (type) {
            case 0:
                suffix = "";
                break;
            case 2:
                suffix = SkinConfig.BRANCH;
                break;
            case 3:
                suffix = SkinConfig.AGENCY;
                break;
        }
        return suffix;
    }


    /**
     * 返回用户性别
     *
     * @param gender 0男  1女  2保密
     * @return
     */
    public static String getGenderString(int gender) {
        String sex = LeYaoGoApplication.getContext().getString(R.string.man);
        switch (gender) {
            case 0:
                sex = LeYaoGoApplication.getContext().getString(R.string.man);
                break;

            case 1:

                sex = LeYaoGoApplication.getContext().getString(R.string.woman);
                break;

            case 2:
                sex = LeYaoGoApplication.getContext().getString(R.string.unknown);
                break;

        }
        return sex;
    }

    /**
     * 获取recyclerView 滑动的 Y 距离
     *
     * @return
     */
    public static int getScrollYDistance(LoadMoreRecyclerView recyclerView) {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        int position = layoutManager.findFirstVisibleItemPosition();
        View firstVisibleChildView = layoutManager.findViewByPosition(position);
        int itemHeight = firstVisibleChildView.getHeight();
        return (position) * itemHeight - firstVisibleChildView.getTop() + (position > 0 ? recyclerView.getHeaderAndFooterRecyclerViewAdapter().getFirstHeader().getHeight() : 0);
    }

    /**
     * 获得上传图片集合
     *
     * @param list
     * @return
     */
    public static List<File> getUploadFileList(List<String> list) {
        List<File> fileList = new ArrayList<>();
        for (String file : list) {
            fileList.add(new File(file));
        }
        return fileList;
    }

    /**
     * 显示选择图片对话框
     */
    public static void showSelectPhotoDialog(Context context, final PickPhotos.OnHandlerResultCallback onHandlerResultCallback) {
        final ActionSheetDialog dialog = new ActionSheetDialog(context, DataProviderUtils.getSelectPhotoItems(), null);
        dialog.isTitleShow(false).layoutAnimation(null).innerAnimDuration(250).show();
        dialog.setOnDialogItemClickL(new OnDialogItemClickListener() {
            @Override
            public void onDialogItemClick(AdapterView<?> parent, View view, int position, long id) {
                dialog.dismiss();
                switch (position) {
                    //从手机相册中选择
                    case 0:
                        PickPhotos.openGallerySingle(1000, onHandlerResultCallback);
                        break;

                    //拍照
                    case 1:
                        PickPhotos.openCamera(2000, onHandlerResultCallback);
                        break;
                }
            }
        });
    }

    /**
     * 居中显示圆角dialog
     */
    public static AlertDialog showCornerDialog(Context context, View view, float width, float height) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.Dialog);
        builder.setView(view);
        AlertDialog ad = builder.create();  //创建对话框
        ad.show();
        Window dialogWindow = ad.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        lp.width = dp2px(width); // 宽度
        lp.height = dp2px(height); // 高度
        dialogWindow.setAttributes(lp);
        return ad;
    }

    /**
     * 居中显示圆角成功dialog
     */
    public static AlertDialog showCornerSuccessDialog(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.Dialog_FS);
        builder.setView(R.layout.corner_success_dialog);
        AlertDialog ad = builder.create();  //创建对话框
        ad.show();
        Window dialogWindow = ad.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        lp.width = dp2px(130); // 宽度
        lp.height = dp2px(134); // 高度
        dialogWindow.setAttributes(lp);
        return ad;
    }

    /**
     * 保存微信获取access_token时返回的WXAccessTokenInfo对象信息
     *
     * @param tokenInfo
     */
    public static void putWXLoginAccessTokenInfo(WXAccessTokenInfo tokenInfo) {
        LeYaoGoApplication.getDataKeeper().put(LoginConfig.WEIXIN_ACCESS_TOKEN_INFO, tokenInfo);
    }


    /**
     * 获取WXAccessTokenInfo对象中的refresh_token字段
     */
    public static String getRefreshToken() {
        WXAccessTokenInfo wxAccessTokenInfo = (WXAccessTokenInfo) LeYaoGoApplication.getDataKeeper().get(LoginConfig.WEIXIN_ACCESS_TOKEN_INFO);
        if (wxAccessTokenInfo == null) {
            return "";
        }
        return wxAccessTokenInfo.getRefresh_token();
    }

    /**
     * 获取商品sku id
     *
     * @param goods
     */
    public static long getSKUId(ShoppingCartGood goods) {
        long id = 0;
        GoodsSKU skuGood = getSkuGood(goods);
        if (skuGood != null) {
            id = skuGood.getGoodsSkuId();
        }
        return id;
    }

    /**
     * 获取商品商品 id
     *
     * @param goods
     */
    public static long getGoodId(ShoppingCartGood goods) {
        long id = 0;
        GoodsSKU skuGood = getSkuGood(goods);
        if (skuGood != null) {
            id = skuGood.getGoodsSkuId();
        } else {
            id = goods.getGoodsId();
        }
        return id;
    }

    /**
     * 获取SKU商品
     *
     * @return
     */
    public static GoodsSKU getSkuGood(ShoppingCartGood goods) {
        GoodsSKU goodsSKU = null;
        if (goods.getGoodsType() == 1) {//sku
            if (goods.getSku() != null && goods.getSku().size() > 0) {
                goodsSKU = goods.getSku().get(0);
            }
        }
        return goodsSKU;
    }

    /**
     * 获取商品库存数量
     *
     * @return
     */
    public static int getStockNumber(ShoppingCartGood good) {//库存类型 0 无限制 1 SPU独立库存 2 SKU共享库存 3 SKU独立库存 ,
        int count = 0;
        switch (good.getStockType()) {
            case 0:
                if (good.getStockStatus() == 1) {
                    count = 0;
                } else {
                    count = good.getStockNumber();
                    if (good.getSku() != null && good.getSku().size() > 0) {
                        count += good.getSku().get(0).getStockNumber();
                    }
                }
                break;
            case 1:
            case 2:
                if (good.getStockStatus() == 1) {
                    count = 0;
                } else {
                    count = good.getStockNumber();
                }
                break;
            case 3:
                if (good.getStockStatus() == 1) {//库存不足
                    count = 0;
                } else {
                    if (good.getSku() != null && good.getSku().size() > 0) {
                        count = good.getSku().get(0).getStockNumber();
                    }
                }
                break;
        }
        return count;
    }


    /**
     * 获取商品库存库存状态
     *
     * @return
     */
    public static int getStockStatus(ShoppingCartGood good) {//stockStatus (integer, optional): 库存状态 0库存充足 1库存不足 2库存紧张 ,
        int count = 0;
        switch (good.getGoodsType()) {
            case 2:
            case 0:
                count = good.getStockStatus();
                break;
            case 1:
                if (good.getSku() != null && good.getSku().size() > 0) {
                    count = good.getSku().get(0).getStockStatus();
                }
                break;
        }
        return count;
    }

    /**
     * 匹配满足活动的商品，匹配到 mUseList会删除匹配的商品
     */
    public static ShoppingCartFragment.ACRecord matchActivityGood(BaseActivityInfo activityInfo, int type, List<ShoppingCartGood> mUseList) {
        ShoppingCartFragment.ACRecord record = new ShoppingCartFragment.ACRecord();
        record.list = new ArrayList<>();
        for (BaseActivityInfo.Good activityGood : activityInfo.getGoodsList()) {
            ShoppingCartGood isMatchGood = null;
            boolean isMatch = false;
            //            CLog.i("hcy","*********************************mUseList.size = "+mUseList.size());
            for (ShoppingCartGood good : mUseList) {
                isMatchGood = good;
                if (activityGood.getGoodsId() == good.getGoodsId() && activityGood.getGoodsSkuId() == Utils.getSKUId(good)) {//满足
                    good.setActivity(true);
                    good.setActivityType(type);//设置活动类型
                    if (type == FREE || type == SUBTRACT) {
                        if (type == SUBTRACT) {//满减，设置减的价格
                            ActivitySubtract subtract = (ActivitySubtract) activityInfo;
                            good.setCutPrice(subtract.getCutPrice());
                            good.setCutFullPrice(subtract.getFullPrice());
                            good.setLimitCount(activityGood.getLimitBuyNumber());//限购数量
                        }
                        record.list.add(good);
                        if (good.isChecked()) {//是选中的商品才加入价格计算
                            int count = good.getNumber();
                            if (good.getLimitCount() != 0 && good.getNumber() > good.getLimitCount()) {
                                count = good.getLimitCount();
                            }
                            record.totalPrice = calculatePrice(record.totalPrice, Utils.getGoodPrice(good), count);
                        }
                        isMatch = true;
                        break;
                    } else {//判断购买数量是否满足
                        good.setLimitCount(activityGood.getLimitBuyNumber());//设置限购数量
                        //                        if (good.getNumber() <= activityGood.getLimitBuyNumber()) {//满足
                        good.setPriceType(activityGood.getPriceType());
                        if (activityGood.getPriceType() == 0) {//价格特价
                            good.setDiscountPrice(activityGood.getPrice());
                        } else {//打折
                            //两个小数相乘,金额需要保留2位小数
                            double f = mul(Utils.getGoodPrice(good), mul(activityGood.getPrice(), 0.01));
                            BigDecimal b = new BigDecimal(f);
                            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            good.setDiscountPrice(f1  /*mul(Utils.getGoodPrice(good), mul(activityGood.getPrice(), 0.01))*/);
                        }
                        record.list.add(good);
                        isMatch = true;
                        break;
                        //                        }
                    }
                }
                //                CLog.i("hcy","good id = "+good.getGoodsId()+"---name = "+good.getGoodsName());
            }
            if (isMatch) {
                //                CLog.i("hcy","isMatchGood good id = "+isMatchGood.getGoodsId()+"---isMatchGood name = "+isMatchGood.getGoodsName());
                mUseList.remove(isMatchGood);
            }
        }
        return record;
    }

    /**
     * 选中商品满足活动的集合，活动id为key
     *
     * @return
     */
    public static LongSparseArray<List<ShoppingCartGood>> getCheckGoodMatchActivity(List<ShoppingCartGood> selectGoodList, List<ShopActivityInfo> activityList) {
        LongSparseArray<List<ShoppingCartGood>> mActivityGoodsArray = new LongSparseArray<>();
        List<ShoppingCartGood> matchList = new ArrayList<>();
        matchList.addAll(selectGoodList);
        for (ShopActivityInfo activityInfo : activityList) {
            switch (activityInfo.getActivityType()) {
                case ShoppingCartFragment.NEW://新人专享
                    BaseActivityInfo newActivityInfo = new Gson().fromJson(activityInfo.getActivityJson(), BaseActivityInfo.class);
                    ShoppingCartFragment.ACRecord newRecord = Utils.matchActivityGood(newActivityInfo, activityInfo.getActivityType(), matchList);
                    if (newRecord.list.size() > 0) {//有满足活动
                        mActivityGoodsArray.append(activityInfo.getActivityId(), newRecord.list);
                    }
                    break;
                case ShoppingCartFragment.SALE://特价
                    BaseActivityInfo saleActivityInfo = new Gson().fromJson(activityInfo.getActivityJson(), BaseActivityInfo.class);
                    ShoppingCartFragment.ACRecord saleRecord = Utils.matchActivityGood(saleActivityInfo, activityInfo.getActivityType(), matchList);
                    for (ShoppingCartGood good : saleRecord.list) {
                        CLog.i("hcy", "saleRecord good=" + good.getGoodsId());
                    }
                    if (saleRecord.list.size() > 0) {//有满足活动
                        mActivityGoodsArray.append(activityInfo.getActivityId(), saleRecord.list);
                    }
                    break;
                case ShoppingCartFragment.FREE://包邮
                    ActivityFree activityFree = new Gson().fromJson(activityInfo.getActivityJson(), ActivityFree.class);
                    ShoppingCartFragment.ACRecord freeRecord = Utils.matchActivityGood(activityFree, activityInfo.getActivityType(), matchList);
                    if (freeRecord.totalPrice >= activityFree.getFullPrice()) {//价格是否满足
                        mActivityGoodsArray.append(activityInfo.getActivityId(), freeRecord.list);
                    }
                    break;
                case ShoppingCartFragment.SUBTRACT://满减
                    ActivitySubtract activitySubtract = new Gson().fromJson(activityInfo.getActivityJson(), ActivitySubtract.class);
                    ShoppingCartFragment.ACRecord subRecord = Utils.matchActivityGood(activitySubtract, activityInfo.getActivityType(), matchList);
                    if (subRecord.totalPrice >= activitySubtract.getFullPrice()) {//满足
                        mActivityGoodsArray.append(activityInfo.getActivityId(), subRecord.list);
                    }
                    break;
            }
        }
        return mActivityGoodsArray;
    }

    /**
     * 设置商品实际总金额，后台计算返回
     */
    public static void setGoodAmountPrice(List<ShoppingCartGood> checkList, List<OrderItem> orderItems) {
        for (OrderItem orderItem : orderItems) {
            for (ShoppingCartGood good : checkList) {
                if (good.getGoodsId() == orderItem.getGoodsId() && Utils.getSKUId(good) == orderItem.getGoodsSkuId()) {
                    good.setAmountPrice(orderItem.getAmountPrice());
                    good.setOrderAllotPrice(orderItem.getOrderAllotPrice());
                    break;
                }
            }
        }
    }

    /**
     * 计算活动抵扣
     */
    public static ShoppingCartFragment.ActivityDiscount getActivityDisCountPrice(LongSparseArray<List<ShoppingCartGood>> array) {
        ShoppingCartFragment.ActivityDiscount activityDiscount = new ShoppingCartFragment.ActivityDiscount();
        for (int i = 0; i < array.size(); i++) {
            CLog.i("hcy", "*////////////////////////////////*");
            for (ShoppingCartGood good : array.valueAt(i)) {
                switch (good.getActivityType()) {
                    case ShoppingCartFragment.NEW://新人专享(和特价计算一样)
                        //                        double discountPrice = NumberUtlis.div(good.getPrice(),good.getDiscountPrice());
                        //                        discountPrice = NumberUtlis.mul(discountPrice,good.getNumber());
                        //                        activityDiscount.discountPrice = NumberUtlis.add(activityDiscount.discountPrice,discountPrice);
                        //                        break;
                    case ShoppingCartFragment.SALE://特价
                        CLog.i("hcy", "good.getDiscountPrice()=" + good.getDiscountPrice());
                        double discountPrice = NumberUtlis.sub(good.getPrice(), good.getDiscountPrice());
                        int num = good.getNumber();
                        if (good.getLimitCount() != 0 && num > good.getLimitCount()) {//如果购买数量大于限购数量，按限购数量计算抵扣的价格
                            num = good.getLimitCount();
                        }
                        discountPrice = mul(discountPrice, num);
                        activityDiscount.discountPrice = NumberUtlis.add(activityDiscount.discountPrice, discountPrice);
                        break;
                    case ShoppingCartFragment.FREE://满包邮
                        activityDiscount.isFreeExpress = true;
                        break;
                    case ShoppingCartFragment.SUBTRACT://满减
                        CLog.i("hcy", "good cut Price=" + good.getCutPrice());
                        //减一个满减的价格
                        activityDiscount.discountPrice = NumberUtlis.add(activityDiscount.discountPrice, good.getCutPrice());
                        break;
                }
                if (good.getActivityType() == FREE || good.getActivityType() == SUBTRACT) {
                    CLog.i("hcy", "break.............meiyou ?" + good.getActivityType());
                    break;
                }
            }
            CLog.i("hcy", "activityDiscount.discountPrice=" + activityDiscount.discountPrice);
        }
        return activityDiscount;
    }

    /**
     * 获取拼接的参数
     *
     * @param list
     * @return
     */
    public static ArrayList<String> getJointParams(List<ShoppingCartGood> list) {
        ArrayList<String> resultList = new ArrayList<>();
        StringBuilder idSb = new StringBuilder();
        StringBuilder skuIdSb = new StringBuilder();
        StringBuilder numSb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            ShoppingCartGood good = list.get(i);
            if (i == 0) {
                idSb.append(good.getGoodsId());
                skuIdSb.append(Utils.getSKUId(good));
                numSb.append(good.getNumber());
            } else {
                idSb.append(",").append(good.getGoodsId());
                skuIdSb.append(",").append(Utils.getSKUId(good));
                numSb.append(",").append(good.getNumber());
            }
        }
        resultList.add(idSb.toString());
        resultList.add(skuIdSb.toString());
        resultList.add(numSb.toString());
        return resultList;
    }

    /**
     * 获取满足的活动JSONArray
     */
    public static String getActivityJSONArray(LongSparseArray<List<ShoppingCartGood>> mActivityGoodsArray) {
        JSONArray jsonArr = new JSONArray();
        if (mActivityGoodsArray.size() == 0) {
            return jsonArr.toString();
        }
        for (int i = 0; i < mActivityGoodsArray.size(); i++) {
            JSONObject jObj = null;
            try {
                jObj = new JSONObject();
                jObj.put("activityId", mActivityGoodsArray.keyAt(i));
                JSONArray jArr = new JSONArray();
                for (ShoppingCartGood good : mActivityGoodsArray.valueAt(i)) {
                    JSONObject obj = new JSONObject();
                    obj.put("number", good.getNumber());
                    obj.put("goodsId", good.getGoodsId());
                    obj.put("goodsSkuId", Utils.getSKUId(good));
                    jArr.put(obj);
                }
                jObj.put("activityGoodsList", jArr);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArr.put(jObj);
        }
        return jsonArr.toString();
    }

    /**
     * 计算多个商品价格和
     *
     * @param totalPrice 原来价格
     * @param price      商品价格
     * @param num        购买数量
     * @return
     */
    public static double calculatePrice(double totalPrice, double price, int num) {
        double goodTotalPrice = mul(price, num);
        double total = NumberUtlis.add(totalPrice, goodTotalPrice);
        return total;
    }

    /**
     * 获取商品价格
     *
     * @param good
     * @return
     */
    public static double getGoodPrice(ShoppingCartGood good) {
        double price = 0.0;
        switch (good.getGoodsType()) {
            case 0:
                price = good.getPrice();
                break;
            case 1:
                if (good.getSku() != null && good.getSku().size() > 0) {
                    price = good.getSku().get(0).getPrice();
                }
                break;
            case 2:
                price = good.getPrice();
                break;
        }
        return price;
    }

    /**
     * 获取折扣商品价格
     *
     * @param good
     * @return
     */
    public static double getDiscountPrice(ShoppingCartGood good) {
        //        double price = 0.0;
        //        switch (good.getGoodsType()) {
        //            case 0:
        //                price = good.getDiscountPrice();
        //                break;
        //            case 1:
        //                if (good.getSku() != null && good.getSku().size() > 0) {
        //                    price = good.getSku().get(0).getPrice();
        //                }
        //                break;
        //            case 2:
        //                price = good.getDiscountPrice();
        //                break;
        //        }
        return /*price = */good.getDiscountPrice();
    }

    /**
     * 店铺商品总价格
     *
     * @param list   需要找出list
     * @param shopId 店铺id
     * @return 总价格
     */
    public static double getTotalPriceByShopId(List<ShoppingCartGood> list, long shopId) {
        double totalPrice = 0.0;
        for (ShoppingCartGood good : list) {
            if (shopId == good.getShopId()) {
                double goodTotalPrice = NumberUtlis.mul(getGoodPrice(good), good.getNumber());
                totalPrice = NumberUtlis.add(totalPrice, goodTotalPrice);
            }
        }
        return totalPrice;
    }

    /**
     * 判断商品状态
     *
     * @param good
     * @return
     */
    public static int getGoodState(ShoppingCartGood good) {
        switch (good.getGoodsType()) {
            case 2://组合
            case 0://spu商品
                if (good.getDeleteFlag() == 1) {//删除
                    return STATE_DEL;
                } else {
                    if (good.getStatusCode() == 0 || Utils.getStockNumber(good) == 0) {//下架或者库存为0
                        return good.getStatusCode() == 0 ? STATE_OUT_STOCK : STATE_NOT_ENOUGH;
                    }
                }
                return STATE_USEABLE;
            case 1://sku商品
                if (good.getDeleteFlag() == 1) {//删除
                    return STATE_DEL;
                } else {
                    if (good.getStatusCode() == 0) {//下架
                        return STATE_OUT_STOCK;
                    }
                }
                GoodsSKU goodsSKU = Utils.getSkuGood(good);
                if (goodsSKU != null) {
                    if (goodsSKU.getDeleteFlag() == 1) {//删除
                        return STATE_DEL;
                    } else {
                        if (goodsSKU.getStatusCode() == 1 || Utils.getStockNumber(good) == 0) {
                            return good.getStatusCode() == 0 ? STATE_OUT_STOCK : STATE_NOT_ENOUGH;
                        }
                    }
                }
                return STATE_USEABLE;
            default:
                return STATE_USEABLE;
        }
    }

    /**
     * 计算商品分类总价
     *
     * @param list        商品list
     * @param classifyIds 分类商品id ,隔开多个
     * @return 总价格
     */
    public static double getTotalPriceByClassifyId(List<ShoppingCartGood> list, String classifyIds) {
        List<ShoppingCartGood> goodList = new ArrayList<>();
        goodList.addAll(list);
        double totalPrice = 0.0;
        if (CheckUtils.isEmpty(classifyIds)) {
            return totalPrice;
        }
        String[] classifyIdArr = classifyIds.split(",");
        if (classifyIdArr.length == 0) {
            return totalPrice;
        }
        for (String id : classifyIdArr) {
            long classifyId = Long.valueOf(id);
            List<ShoppingCartGood> containList = new ArrayList<>();
            for (ShoppingCartGood good : goodList) {
                if (classifyId == good.getClassifyId()) {
                    double goodTotalPrice = good.getAmountPrice();//实际金额
                    totalPrice = NumberUtlis.add(totalPrice, goodTotalPrice);
                    containList.add(good);
                }
            }
            goodList.removeAll(containList);//有满足删除，不进行下一次匹配
        }
        return totalPrice;
    }

    /**
     * 计算优惠商品总价
     *
     * @param list           goodList
     * @param couponGoodList 优惠商品
     * @return 价格
     */
    public static double getTotalPriceByGoodId(List<ShoppingCartGood> list, List<CouponGood> couponGoodList) {
        double totalPrice = 0.0;
        if (couponGoodList == null || couponGoodList.size() == 0) {
            return totalPrice;
        }
        List<ShoppingCartGood> goodList = new ArrayList<>();
        goodList.addAll(list);
        for (CouponGood coupon : couponGoodList) {
            List<ShoppingCartGood> containList = new ArrayList<>();
            for (ShoppingCartGood good : goodList) {
                if (coupon.getGoodsId() == good.getGoodsId() && getSKUId(good) == coupon.getGoodsSkuId()) {
                    double goodTotalPrice = good.getAmountPrice();
                    totalPrice = NumberUtlis.add(totalPrice, goodTotalPrice);
                    containList.add(good);
                }
            }
            goodList.removeAll(containList);//有满足删除，不进行下一次匹配
        }
        return totalPrice;
    }

    /**
     * 保存购物车选中的商品id
     *
     * @param detailsInfo
     */
    public static void putShoppingCartUnCheckId(List<Long> detailsInfo) {
        clearShoppingCartUnCheckId();
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.SHOPPING_CART_CHECK_ID, detailsInfo);
    }

    /**
     * 清除购物车选中的商品id
     */
    public static void clearShoppingCartUnCheckId() {
        LeYaoGoApplication.getDataKeeper().remove(CacheConfig.SHOPPING_CART_CHECK_ID);
    }

    /**
     * 获取购物车选中的商品id
     *
     * @return
     */
    public static List<Long> getShoppingCartUnCheckId() {
        return (List<Long>) LeYaoGoApplication.getDataKeeper().get(CacheConfig.SHOPPING_CART_CHECK_ID);
    }

    /**
     * 保存默认收货地址
     *
     * @param address
     */
    public static void putDefaultAddress(Address address) {
        String str = new Gson().toJson(address);
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.DEFAULT_ADDRESS, str);
    }

    /**
     * 清除默认收货地址
     */
    public static void clearDefaultAddress() {
        LeYaoGoApplication.getDataKeeper().remove(CacheConfig.DEFAULT_ADDRESS);
    }

    /**
     * 获取默认地址
     *
     * @return
     */
    public static Address getDefaultAddress() {
        String str = LeYaoGoApplication.getDataKeeper().get(CacheConfig.DEFAULT_ADDRESS, "");
        if (CheckUtils.isEmpty(str)) {
            return null;
        }
        Address address = null;
        try {
            address = new Gson().fromJson(str, Address.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return address;
    }


    /**
     * 保存省列表
     *
     * @param list
     */
    public static void putProvinceList(ArrayList<BaseBean> list) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.PROVINCE_LIST, list);
    }


    /**
     * 获得省列表
     */
    public static ArrayList<BaseBean> getProvinceList() {
        return (ArrayList<BaseBean>) LeYaoGoApplication.getDataKeeper().get(CacheConfig.PROVINCE_LIST);
    }


    /**
     * 保存市编码列表
     *
     * @param list
     */
    public static void putCityCodeList(ArrayList<BaseBean> list) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.CITY_CODE_LIST, list);
    }


    /**
     * 获得市编码列表
     */
    public static ArrayList<BaseBean> getCityCodeList() {
        return (ArrayList<BaseBean>) LeYaoGoApplication.getDataKeeper().get(CacheConfig.CITY_CODE_LIST);
    }


    /**
     * 保存市列表
     *
     * @param list
     */
    public static void putCityList(ArrayList<ArrayList<BaseBean>> list) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.CITY_LIST, list);
    }


    /**
     * 获得市列表
     */
    public static ArrayList<ArrayList<BaseBean>> getCityList() {
        return (ArrayList<ArrayList<BaseBean>>) LeYaoGoApplication.getDataKeeper().get(CacheConfig.CITY_LIST);
    }


    /**
     * 保存区列表
     *
     * @param list
     */
    public static void putDistrictList(ArrayList<ArrayList<ArrayList<BaseBean>>> list) {
        LeYaoGoApplication.getDataKeeper().put(CacheConfig.DISTRICT_LIST, list);
    }


    /**
     * 获得区列表
     */
    public static ArrayList<ArrayList<ArrayList<BaseBean>>> getDistrictList() {
        return (ArrayList<ArrayList<ArrayList<BaseBean>>>) LeYaoGoApplication.getDataKeeper().get(CacheConfig.DISTRICT_LIST);
    }


    /**
     * 获取购物车数量
     *
     * @return
     */
    public static int getShoppingCartNum(List<ShoppingCartGood> shoppingCartGoods) {
        int num = 0;
        if (CheckUtils.isEmpty(shoppingCartGoods))
            return num;
        for (ShoppingCartGood shoppingCartGood : shoppingCartGoods) {
            if (getGoodState(shoppingCartGood) != STATE_USEABLE) {
                continue;
            }
            num += shoppingCartGood.getNumber();
        }
        return num;

    }


    /**
     * 保存首页栏目宽度
     *
     * @param width
     */
    public static void putHomeColumnContainer(int width) {
        LeYaoGoApplication.getDataKeeper().putInt(CacheConfig.HOME_COLUMN_CONTAINER_WIDTH, width);
    }

    /**
     * 获取首页栏目宽度
     */
    public static int getHomeColumnContainer() {
        return LeYaoGoApplication.getDataKeeper().getInt(CacheConfig.HOME_COLUMN_CONTAINER_WIDTH, 0);
    }

    /**
     * 判断是否弹出规则选择pop，只有在goodsType = 1 & goodsSkuId = 0时才弹出Pop
     *
     * @param goodsType
     * @param goodsSkuId
     * @return
     */
    public static boolean isShowSpePop(int goodsType, int goodsSkuId) {
        if (goodsType == 1 && goodsSkuId == 0)
            return true;
        else
            return false;
    }

    /**
     * 显示选择商品规格的popWindow
     *
     * @param context
     * @param rootView
     * @param
     * @param goodsSkuId     商品的goodsSkuId
     * @param picUrl         商品的图片imageView的drawable
     * @param goodsSkuId     商品的goodsSkuId
     * @param skuEntities
     * @param skuMapEntities
     * @param listener
     */
    public static void showSpecPop(Context context, View rootView, int statusCode, String picUrl, int goodsSkuId, int selectedSkuId, List<SkuEntity> skuEntities,
                                   List<SkuMapEntity> skuMapEntities, GoodsSpecPopUtils.OnPopClickListener listener) {

        GoodsSpecPopUtils utils = GoodsSpecPopUtils.getInstance();
        utils.show(context, rootView, statusCode, picUrl, goodsSkuId, selectedSkuId, skuEntities, skuMapEntities, listener);
    }


    /**
     * shareSDK分享
     *
     * @param context
     * @param title
     * @param text
     * @param imageUrl
     */
    public static void showShare(Context context, String title, String text, String imageUrl) {
        ShareUtil.showShare(context, "", title, "http://www.leyao.cn/#page1", text, imageUrl, "http://www.leyao.cn/#page1", "乐摇GO", "http://www.leyao.cn/#page1", "", null);
    }

    /**
     * 第三方登录
     *
     * @param context
     * @param platformName 要登录的平台名称
     * @param listener
     */
    public static void thirdPartyLogin(Context context, String platformName, OnLoginListener listener) {
        ThirdPartyLoginUtil util = new ThirdPartyLoginUtil();
        util.setPlatform(platformName);
        util.setOnLoginListener(listener);
        util.login(context);
    }

    /**
     * 跳转到商品详情 type=0
     *
     * @param activity
     * @param goodsId            商品ID
     * @param goodsSkuId         商品SkuId
     * @param isFromShoppingCart 是否从购物车进入
     */
    public static void startGoodsDetails(Activity activity, int goodsId, int goodsSkuId, boolean isFromShoppingCart) {
        Bundle bundle = new Bundle();
        bundle.putInt(IntentConfig.BUNDLE_GOODS_ID, goodsId);
        bundle.putInt(IntentConfig.BUNDLE_GOODS_SKU_ID, goodsSkuId);
        bundle.putBoolean(IntentConfig.IS_FROM_SHOPPING_CART, isFromShoppingCart);
        startActivity(activity, GoodsActivity.class, bundle);
    }


    /**
     * 跳转到活动专题 type=2 或 type=3
     *
     * @param activity
     * @param activityId
     */
    public static void startActivityDetails(Activity activity, /*int activityType,*/ long activityId, boolean isFromShoppingCart) {
        Bundle bundle = new Bundle();
        bundle.putLong(IntentConfig.ACTIVITY_ID, activityId);
        //        bundle.putInt(IntentConfig.ACTIVITY_TYPE, activityType);
        bundle.putBoolean(IntentConfig.IS_FROM_SHOPPING_CART, isFromShoppingCart);
        Utils.startActivity(activity, SpecialActivityDetailsActivity.class, bundle);
    }

    /**
     * 跳转到商品分类列表 type=1
     *
     * @param activity
     * @param activityId
     */
    public static void startGoodsClassifyList(Activity activity, long activityId, String title) {
        Bundle bundle = new Bundle();
        bundle.putLong(IntentConfig.ACTIVITY_ID, activityId);
        bundle.putString(IntentConfig.ACTIVITY_TITLE, title);
        Utils.startActivity(activity, GoodsClassifyListActivity.class, bundle);
    }

    /**
     * 使用一张图片设置不同的着色效果
     *
     * @param drawable
     * @param colors
     * @return
     */
    public static Drawable tintDrawable(Drawable drawable, ColorStateList colors) {
        Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTintList(wrappedDrawable, colors);
        return wrappedDrawable;
    }

    /**
     * 解析购物车数量加减
     *
     * @param response
     * @param context
     * @return
     * @throws IOException
     * @throws JSONException
     */
    public static GoodsStock parseShopGoodCountJson(Response response, Context context) throws IOException, JSONException {
        String body = response.body().string();
        response.close();
        CLog.e("LogInterceptor", body);
        CLog.json("LogInterceptor", body);
        if (CheckUtils.isEmpty(body))
            return null;
        /**
         * 服务器返回的响应都包含success,errorMsg,errorCode，有些还包含returnValue部分
         */
        JSONObject jsonObject = new JSONObject(body);
        boolean success = jsonObject.optBoolean("success", true);
        final String msg = jsonObject.optString("errorMsg", "");
        int msgCode = jsonObject.optInt("errorCode", 0);
        String result = jsonObject.optString("returnValue", null);
        GoodsStock goodsStock;
        switch (msgCode) {
            case 0:
                /**
                 * msgCode = 0 代表成功，默认实现Gson解析成相应的实体Bean返回，可以自己替换成fastjson等
                 * 对于返回参数，先支持 String，然后优先支持class类型的字节码，最后支持type类型的参数
                 */
                if (success) {
                    //更新TokenId
                    goodsStock = GsonConvert.fromJson(result, GoodsStock.class);
                    goodsStock.setErrorCode(msgCode);
                    return goodsStock;
                } else {
                    OkHttpUtils.getInstance().getDelivery().post(() -> {
                        showToast(context, msg);
                    });
                    CLog.e("LogInterceptor", "错误代码：" + msgCode + "，错误信息：" + msg);
                    throw new IllegalStateException(msgCode + "");
                }
            case 10020://库存不足
                goodsStock = GsonConvert.fromJson(result, GoodsStock.class);
                goodsStock.setErrorCode(msgCode);
                return goodsStock;
            default:
                if (context.getString(R.string.stock_no).equals(msg)) {
                    goodsStock = GsonConvert.fromJson(result, GoodsStock.class);
                    goodsStock.setErrorCode(msgCode);
                    return goodsStock;
                }
                OkHttpUtils.getInstance().getDelivery().post(() -> {
                    showToast(context, msg);
                });
                CLog.e("LogInterceptor", "错误代码：" + msgCode + "，错误信息：" + msg);
                throw new IllegalStateException(msgCode + "");
        }
    }

    /**
     * 解析填写订单 配送判断详细说明，失败返回解析对象
     *
     * @param response
     * @param context
     * @return
     * @throws IOException
     * @throws JSONException
     */
    public static Express parseExpressJson(Response response, Context context) throws IOException, JSONException {
        String body = response.body().string();
        response.close();
        CLog.e("LogInterceptor", body);
        CLog.json("LogInterceptor", body);
        if (CheckUtils.isEmpty(body))
            return null;
        /**
         * 服务器返回的响应都包含success,errorMsg,errorCode，有些还包含returnValue部分
         */
        JSONObject jsonObject = new JSONObject(body);
        boolean success = jsonObject.optBoolean("success", true);
        final String msg = jsonObject.optString("errorMsg", "");
        int msgCode = jsonObject.optInt("errorCode", 0);
        String result = jsonObject.optString("returnValue", null);
        Express express;
        switch (msgCode) {
            case 0:
                /**
                 * msgCode = 0 代表成功，默认实现Gson解析成相应的实体Bean返回，可以自己替换成fastjson等
                 * 对于返回参数，先支持 String，然后优先支持class类型的字节码，最后支持type类型的参数
                 */
                if (success) {
                    express = GsonConvert.fromJson(result, Express.class);
                    express.setExpress(true);
                    return express;
                } else {
                    OkHttpUtils.getInstance().getDelivery().post(() -> {
                        showToast(context, msg);
                    });
                    CLog.e("LogInterceptor", "错误代码：" + msgCode + "，错误信息：" + msg);
                    throw new IllegalStateException(msgCode + "");
                }
            case 10002://不在配送范围
                express = new Express();
                express.setExpress(false);
                return express;
            default:
                if (context.getString(R.string.express_no).equals(msg)) {
                    express = new Express();
                    express.setExpress(false);
                }
                OkHttpUtils.getInstance().getDelivery().post(() -> {
                    showToast(context, msg);
                });
                CLog.e("LogInterceptor", "错误代码：" + msgCode + "，错误信息：" + msg);
                throw new IllegalStateException(msgCode + "");
        }
    }

    private static void showToast(Context context, String msg) {
        //        XTipsDialog.showFail(context, msg);
        XToastUtils.showShortToast(msg);
    }

    /**
     * 获取商品轮播图的图片或者商品详情中的图片
     *
     * @param goodsDetails
     * @param type         商品文件类型 0 商品图片 1 商品详情图片
     * @return
     */
    public static List<String> getGoodsFiles(GoodsDetails goodsDetails, int type) {
        List<GoodsDetails.GoodsFileEntity> goodsFiles = goodsDetails.getGoodsFile();
        List<String> goodsDetailFiles = new ArrayList<String>();
        if (goodsFiles != null && goodsFiles.size() != 0) {
            for (GoodsDetails.GoodsFileEntity goodsFile : goodsFiles) {
                if (goodsFile.getGoodsFileType() == type) {
                    goodsDetailFiles.add(goodsFile.getFileMd5());
                }
            }
        }
        return goodsDetailFiles;
    }

    /**
     * 验证手机号是否有非法字符
     *
     * @param phoneNo
     * @return
     */
    public static boolean isPhoneNumber(String phoneNo) {
        boolean isV = false;
        if (phoneNo.matches("^[0-9]*$")) {
            isV = true;
        }
        return isV;
    }


    /**
     * 计算折扣价
     *
     * @param price   销售价
     * @param account 折扣
     * @return
     */
    public static double calculateAccountPrice(double price, double account) {
        if (price == 0.0 || account == 0.0) {
            return 0.00;
        }
        return NumberUtlis.mul(NumberUtlis.mul(price, account), 0.01);
    }

    //跳转登录界面
    public static void gotoLogin() {
        gotoLogin(0);
    }

    //跳转登录界面
    public static void gotoLogin(int loginState) {
        Intent intent = new Intent(LeYaoGoApplication.getContext(), QuickLoginActivity.class);
        intent.putExtra(IntentConfig.LOGIC_CODE, loginState);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        LeYaoGoApplication.getContext().startActivity(intent);
    }

    /**
     * 判断用户是否登录
     *
     * @param loginState 逻辑状态 用于登录成功后继续执行下一步操作
     * @return
     */
    public static void startLogin(int loginState) {
        Intent intent = new Intent(LeYaoGoApplication.getContext(), LoginActivity.class);
        intent.putExtra(IntentConfig.LOGIC_CODE, loginState);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        LeYaoGoApplication.getContext().startActivity(intent);
    }

    /**
     * 打开网销卡列表页面
     *
     * @param activity
     * @param isFromHome
     */
    public static void openRechargeSaleCard(Activity activity, boolean isFromHome) {
        Bundle bundle = new Bundle();
        bundle.putBoolean(IntentConfig.IS_FROM_HOME, isFromHome);
        startActivity(activity, RechargeSaleCardActivity.class, bundle);
    }

}
